import { Vue, Component, Watch } from 'vue-property-decorator'
import styles from './styles.less'
import Login from './Login/Login'
import { Mutation, State, Action } from 'vuex-class'
import { RootState } from '@/store'
import { Route } from 'vue-router'
Component.registerHooks(['beforeRouteLeave'])

const navList = [
  {
    id: 1,
    name: '返回首页',
    hoverName: '返回首页',
    width: '81px',
    img: 'homepage',
  },
  {
    id: 3,
    name: '热线电话',
    hoverName: '热线电话',
    phone: '4000878198转3',
    width: '240px',
    img: 'phone',
  },
  {
    id: 4,
    name: '扫码加入',
    hoverName: '扫码加入',
    width: '81px',
    img: 'scan-icon',
  },
  {
    id: 5,
    name: '常见问题',
    hoverName: '常见问题',
    width: '81px',
    img: 'faq',
  },
  {
    id: 6,
    name: '返回顶部',
    hoverName: '返回顶部',
    width: '81px',
    img: 'top',
  },
]

@Component({})
export default class HomePage extends Vue {
  // cMapsUrl: string = 'https://unpkg.com/pdfjs-dist@2.1.266/cmaps/'
  // cMapsUrl: string = '//unpkg.com/pdfjs-dist@2.1.266/cmaps/'
  // workerSrc: string = '//mozilla.github.io/pdf.js/build/pdf.worker.js'
  navId = null
  redirect = ''
  gotInfo = false
  showNav = true
  showCode = false
  @State((state: RootState) => state.user.accountName)
  name!: string

  @State((state: RootState) => state.user.dingUserId)
  dingUserId!: string

  @Action('user/info') userInfo!: any
  @Action('login/logout') logout!: any
  @Mutation('user/setStateData') setUserStateData!: any
  @State((state: RootState) => state.login.showLogin)
  showLogin!: boolean
  @Mutation('login/setStateData') setStateData!: any
  protected render() {
    return (
      <div class={styles.homepage}>
        <div class={styles.header}>
          <span>
            <img
              src={require('@/assets/header-logo.png')}
              width="auto"
              height="40px"
              onClick={() => {
                this.$router.push({ name: 'homepage' })
              }}
            />
          </span>
          {this.gotInfo &&
            (!!this.name ? (
              <div class={{ [styles.info]: true }}>
                <span class={styles.name} onClick={this.toUserInfo}>
                  {this.gotInfo && !this.dingUserId && (
                    <div class={styles.redPoint} />
                  )}
                  <img src={require('@/assets/avatar.png')} />
                  {this.name || '--'}
                </span>
                <span class={styles.splice} />
                <a onClick={this.quit} class={styles.logout}>
                  退出
                </a>
              </div>
            ) : (
              <span class={styles.loginBtn}>
                <el-button type="text" onClick={this.toSignup}>
                  新用户注册
                </el-button>
                <el-button type="primary" onClick={this.loginEvent}>
                  登录
                </el-button>
              </span>
            ))}
        </div>
        <div class={styles.content} id="content">
          <router-view />
        </div>
        <div class={styles.footer}>
          <div class={styles.center}>
            <p class={styles.part}>
              <p class={styles.title}>联系我们</p>
              <p class={styles.text}>
                <p class="f21">4000878198转3</p>
                <p class="f14">(政务服务专线)</p>
              </p>
            </p>
            <p class={styles.part}>
              <p class={styles.title}>相关站点</p>
              <p class={styles.text}>
                <a target="_blank" href="http://www.zjzwfw.gov.cn/">
                  浙江政务服务网（浙里办）
                </a>
                <br />
                <a target="_blank" href="http://ra.zj.gov.cn/">
                  国家电子政务外网浙江省电子认证注册服务中心（ZJCA）
                </a>
                <br />
                <a target="_blank" href={`${window.config.oldVersionUrl}`}>
                  浙江省政府电子印章系统（旧版）
                </a>
                <br />
                <a target="_blank" href={`${window.config.manageSystemUrl}`}>
                  浙江省政府电子印章管理系统（后台管理）
                </a>
              </p>
            </p>
            <p class={styles.part}>
              <p class={styles.text}>
                <img src={require('@/assets/login-qrcode.jpg')} alt="" />
                <br />
                <p>
                  {window.config.dingGroupName}
                  <br />
                  钉钉APP扫码，以获得更多技术支持
                </p>
              </p>
            </p>
          </div>
          <div class={styles.support}>
            主办单位：浙江省大数据发展管理局
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;技术支持：杭州天谷信息科技有限公司
          </div>
        </div>
        <ul
          class={{ [styles.navigation]: true, [styles.active]: this.showNav }}
        >
          {!this.navId && (
            <div class={styles.hideBtnBox}>
              <div
                class={styles.hideBtn}
                onClick={() => {
                  this.showNav = !this.showNav
                }}
              >
                <div v-show={this.showNav} class={styles.right}>
                  {/* <img src={require("@/assets/right.png")} alt="" width="15px" height="86px"/> */}
                </div>{' '}
                <div v-show={!this.showNav} class={styles.left}>
                  {/* <img src={require("@/assets/left.png")} alt="" width="15px" height="86px" /> */}
                </div>
              </div>
            </div>
          )}
          {navList.map((item: any) => {
            return (
              <el-popover
                placement="left"
                open-delay={220}
                trigger="hover"
                disabled={item.id !== 4 || !this.showNav}
                width={150}
                title={window.config.dingGroupName}
                popper-class="popover-hover"
              >
                <p class="mt4">
                  <img
                    src={require('@/assets/login-qrcode.jpg')}
                    alt=""
                    width="100px"
                    height="100px"
                  />
                </p>
                <li
                  slot="reference"
                  style={{
                    width: item.id === this.navId ? item.width : '67px',
                  }}
                  class={{
                    [styles.navItem]: true,
                    [styles.activeItem]: item.id === this.navId,
                  }}
                  key={item.id}
                  {...{
                    on: {
                      mouseover: () => {
                        if (!this.showNav) return
                        this.navId = item.id
                      },
                      mouseleave: () => {
                        this.navId = null
                      },
                      click: () => {
                        if (!this.showNav) return
                        this.navHandler(item)
                      },
                    },
                  }}
                >
                  <div class={styles.centers}>
                    <img
                      src={require(`@/assets/${item.img}.png`)}
                      alt=""
                      width="23px"
                      height="auto"
                    />
                    <p>{item.id === this.navId ? item.hoverName : item.name}</p>
                  </div>
                  {item.id === this.navId && item.phone && (
                    <div class={styles.rightCenters}>{item.phone}</div>
                  )}
                </li>
              </el-popover>
            )
          })}
        </ul>
        <section
          class={[styles.loginWrapper, { [styles.show]: this.showLogin }]}
          // onMousedown={this.mousedownEvt}
          // onMouseup={this.mouseupEvt}
        >
          <img
            class="close-icon"
            src={require('@/assets/close.png')}
            onClick={this.closeEvt}
            width="60px"
            height="60px"
          />

          <transition name="slide-fade">
            <Login
              v-show={this.showLogin}
              ref="login"
              onSuccess={this.loginSuccess}
            />
          </transition>
        </section>
      </div>
    )
  }

  mounted() {
    const login = !!this.$route.query.login
    this.clearInfo()
    this.getUserInfo(login)
  }

  navHandler(item: any) {
    switch (item.id) {
      case 1:
        this.$router.push({ name: 'first' })
        break
      case 2: // 技术支持
        // this.$router.push({ name: 'support'})
        window.open(`${window.location.origin}/support`, '_blank')
        break
      case 5: // 常见问题
        this.$router.push({ name: 'faq' })
        break

      case 6: // 返回顶部
        this.toTop()
        break
      default:
        break
    }
  }

  toSignup() {
    this.$router.push({ name: 'signup' })
  }

  closeEvt() {
    this.redirect = ''
    this.setStateData({ showLogin: false })
  }

  beforeDestroy() {
    this.setStateData({ showLogin: false })
  }

  getUserInfo(login: boolean) {
    return this.userInfo(true)
      .then((res: any) => {
        this.gotInfo = true
      })
      .catch((e: any) => {
        this.gotInfo = true
        this.setStateData({ showLogin: login })
      })
  }

  toUserInfo() {
    this.$router.push({ name: 'userInfo' })
  }

  quit() {
    this.logout()
    this.clearInfo()
  }

  clearInfo() {
    this.setUserStateData({
      accountLicenseNumber: '',
      accountLicenseType: 1,
      accountMobile: '',
      accountName: '',
      accountUUID: '',
      organizeAdministrationLevel: 1,
      organizeLicenseNumber: '',
      organizeLicenseType: 2,
      organizeName: '',
      organizeType: 3,
      organizeUUID: '',
      accountEmail: '',
      bindDingUserVisible: false,
      dingUserId: '',
    })
  }

  loginSuccess() {
    this.$message.success('登录成功')
    if (!!this.redirect) {
      // 重定向
      this.setStateData({ showLogin: false })
      this.$router.push({ path: this.redirect })

      // this.redirect = ''
    } else {
      this.setStateData({ showLogin: false })
      this.getUserInfo(false)
    }
  }

  toTop() {
    const el = this.$el.querySelector('#content') as Element
    if (!!el && typeof el.scrollIntoView === 'function') {
      // 定位页面中间
      el.scrollIntoView({ block: 'start', behavior: 'smooth' })
    }
  }

  beforeRouteLeave(to: Route, from: Route, next: any) {
    if (to.path.indexOf('/home/') === -1) {
      next()
    } else {
      // 跳转列表或内部页面
      // next()
      if (!this.name && !this.redirect) {
        // 未登录直接弹窗登录
        this.redirect = to.path
        this.clearInfo()
        this.loginEvent()
      } else {
        this.userInfo(true)
          .then((res: any) => {
            next()
          })
          .catch((e: any) => {
            if (e === 'LOGIN_INVALID') {
              // 登录失效
              this.redirect = to.path
              this.clearInfo()
              this.loginEvent()
            }
          })
      }
    }
  }

  loginEvent() {
    this.setStateData({ showLogin: true })
  }

  @Watch('showLogin')
  loginChange(val: boolean) {
    if (!val) {
      ;(this.$refs['login'] as any) &&
        (this.$refs['login'] as any).reset &&
        (this.$refs['login'] as any).reset()
      // document.documentElement.style.overflowY = 'auto';//恢复
      // document.documentElement.style.marginRight="0px";
      // this.$router.replace({ name: 'homepage' })
    } else {
      // document.documentElement.style.overflowY = 'hidden';//禁用滚动条
      // document.documentElement.style.marginRight=window.innerWidth-document.body.clientWidth+"px";
      if (this.$route.name === 'first' && !!this.$route.query.login) {
        // 首页替换路由并去除参数
        this.$router.replace({ name: 'first' })
      }
    }
  }

  @Watch('$route')
  routerUpdate(to: Route, from: Route) {
    this.$nextTick(() => {
      this.toTop()
    })
  }

  @Watch('navId')
  navIdChange(val: any) {
    if (val === 4) {
      setTimeout(() => {
        // 设置超时
        this.showCode = true
      }, 220)
    } else {
      setTimeout(() => {
        // 设置超时
        this.showCode = false
      }, 220)
    }
  }
}
